﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GameMatchControl.Layout;
using GameEngine;

namespace GameMatchControl.LayoutEngine
{
    /// <summary>
    /// Class for building inline type of layout
    /// </summary>
    internal class InlineLayoutBuilder: AbstractLayoutBuilder
    {
        /// <summary>
        /// Branch entering method
        /// </summary>
        protected override void EnteringBranch(GameTree parent)
        {
            // No work to do
        }

        /// <summary>
        /// Branch leaving method
        /// </summary>
        protected override void LeavingBranch(GameTree parent)
        {
            if (parent.IsRoot() || parent.GetNodeType() == eGameType.Variation)
            {
                PopArea();
            }
        }

        /// <summary>
        /// Item processing method override
        /// </summary>
        protected override Area ProcessNode(GameTree treeItem, GameManager gm)
        {
            if (treeItem.IsRoot())
            {
                // create root ara
                GameMatchArea root = AreaFactory.CreateGameMatchArea(treeItem);

                // push the content area to the stack
                root.Content = AreaFactory.CreateInlineContentArea();
                PushArea(root.Content);

                return root;
            }
            else if (treeItem.GetNodeType() == eGameType.Variation)
            {
                // create area
                VariationArea varArea = AreaFactory.CreateItemArea(treeItem, gm) as VariationArea;

                // put to the content area
                if ((StackTop() is ContentArea) == false)
                    throw new Exception("Not Content Area");
                (StackTop() as ContentArea).AddArea(varArea);

                // create nested content area
                varArea.Content = AreaFactory.CreateInlineContentArea();
                PushArea(varArea);

                return varArea;                             
            }
            else if (AreaFactory.IsItemArea(treeItem))
            {
                // create area and put into the content area
                Area area = AreaFactory.CreateItemArea(treeItem, gm);
                
                if ((StackTop() is ContentArea) == false)
                    throw new Exception("Not Content Area");
                (StackTop() as ContentArea).AddArea(area);

                return area;
            }
            else
            {
                throw new Exception("Unknown GameTree type.");
            }
        }
    }
}
